import { useToken } from "@/components/windows/hooks/use-token";
import axios, { type AxiosResponse, type InternalAxiosRequestConfig } from "axios";

const authenticated = computed(() => !!useToken().getToken());
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000,
});

service.interceptors.request.use(
  (cfg) => {
    const tokenRequired = (cfg.headers || {}).tokenRequired === false;
    if (tokenRequired) {
      cfg.headers.Authorization = `Bearer ${tokenRequired}`;
    }
    return cfg;
  },
  (e) => {
    Promise.reject(e).then((r) => r);
  },
);

service.interceptors.response.use(
  (res) => {
    return Promise.resolve(res.data);
  },
  (err) => {
    console.log("Error: ", err);
    const res = err.response?.data ?? {}
    let { message } = res;
    return Promise.reject(message);
  },
);
//参数类型
export type RequestParams = { url: string; params?: any; data?: any };
//返回值类型
export type ResultType<T> = Promise<{ data: T, code: number, message: string }>
// 2. 专门为DELETE请求扩展参数类型
export type DeleteRequestParams = RequestParams & {
  id: string | number; // 必选参数
  pathAsId?: boolean; // 可选配置：是否将id拼接到路径中
};
/**
 * GET请求
 * @param requestParams
 */
export const madokaGet = (requestParams: RequestParams) => {
  const { url, data, params } = requestParams;
  return service.get(url, { params, data });
};
/**
 * POST请求
 * @param requestParams
 */
export const madokaPost = <T>(requestParams: RequestParams): ResultType<T> => {
  const { url, params, data } = requestParams;
  return service.post(url, data, { params });
};
/**
 * PUT请求
 * @param requestParams
 */
export const madokaPut = (requestParams: RequestParams) => {
  const { url, params, data } = requestParams;
  return service.put(url, data, { params });
};
/**
 * DELETE请求
 * @param requestParams
 */
export const madokaDelete = (requestParams: DeleteRequestParams) => {
  let { url, params, data, id } = requestParams;
  if (id) {
    url = `${url}/${id}`;
  }
  return service.delete(url, { params, data });
};
